<script>
import store from "@/store";
import UButton from "../../uni_modules/uview-ui/components/u-button/u-button.vue";
import {request} from "../../static/core/request";
import {getAuth, getUserInfoApi} from "../../api/common/user";
// const CryptoJS = require("crypto-js");
import CryptoJS from 'crypto-js'
import {getTime} from "../../api/common/common";
export default {
  name: "index",
  components: {UButton},
  data() {
    return {
      username: "",
      password: "",
      agreement: [],
      loading: false,
      status: 0, // 0 获取token中 1 获取到token
      hasPhone: false,
      token: null,
      userInfo: null,
      auth: true,
    };
  },
  computed: {

  },
  methods: {
    toIndex(){
      // if(!this.auth){
      //   uni.showToast({
      //     title: '\u5df2\u8d85\u8fc7\u7cfb\u7edf\u671f\u9650\uff0c\u65e0\u6cd5\u4f7f\u7528\u7cfb\u7edf\u529f\u80fd',
      //     icon: 'none',
      //     duration: 2000
      //   });
      //   return;
      // }
      uni.reLaunch({
        url: "/pages/index/index"
      });
    },
    async loginClick(){
      if (!this.agreement.includes('agreement')) {
        this.showTip();
      } else {
        await store.dispatch("user/saveLogin", {
          token: this.token,
          userInfo: this.userInfo,
        });
        this.toIndex();
      }
    },
    async checkPhone(){
      const { data } = await getUserInfoApi();
      if(data.phoneNumber) {
        this.hasPhone = true;
      }
    },
    showTip(){
      uni.showToast({
        title: '请阅读并同意《⽤户服务协议和隐私政策》',
        icon: 'none',
        duration: 2000
      })
    },
    // 代码待优化
    async login() {
      const self = this;
      uni.login({
        provider: 'weixin', //使用微信登录
        success: async function (loginRes) {
          this.loading = false;
          const code = loginRes.code;
          if (!code) {
            uni.showToast({
              title: "登录失败",
              icon: "none"
            });
            return;
          }
          request({
            url: "/wxmini/standard/api/wxuser/login",
            method: "POST",
            data: {
              code,
            }
          }).then( async res => {
            self.token = res.data.userToken;
            self.userInfo = res.data;
            if (res.data.wxPhone) {
              self.hasPhone = true;
            }
          })
          this.status = 1;
        }
      });
    },
    toResetPassWord() {
      uni.navigateTo({
        url: "/pages/reset-password/index"
      });
    },
    toAgreement() {
      uni.navigateTo({
        url: "/pages/login/agreement/index"
      });
    },
    groupChange(){
      // this.agreement = !this.agreement;
      console.log(this.agreement)
    },
    handlePhoneNumber(e){
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        request({
          url: "/wxmini/standard/api/wxuser/authUserPhone",
          method: "POST",
          header: {
            userToken: this.token,
            openid: this.userInfo.openid,
          },
          data: {
            code: e.detail.code,
          }
        }).then( data => {
          uni.setStorageSync("token", this.token);
          uni.setStorageSync("userInfo", this.userInfo);
          this.toIndex();
        })
      }
    },
    decrypt(ciphertext, key, iv) {
      // 确保 ciphertext 是 Base64 编码的字符串
      const bytes = CryptoJS.AES.decrypt({
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
      }, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        mode: CryptoJS.mode.CBC, // 加密时使用的模式，CBC 是常见的一个
        padding: CryptoJS.pad.Pkcs7 // 加密时使用的填充方式
      });

      const originalText = bytes.toString(CryptoJS.enc.Utf8);
      return originalText;
    },
    getTime(){
      // 获取时间戳
      let time = new Date().getTime();
      getTime().then(res => {
        console.log(res, 123)
      }).catch(err => {
        try {
          time = err.data.t;
          console.log(time * 2, '*****s*****')
        } catch (e) {
          time = new Date().getTime();
          console.log(time * 2, '*****l*****')
        }
        if (time > 1714924800000) {
          this.auth = false;
        }
      });
    }
  },
  created() {
    var str = 'aEVCSkpCK3hhZk1JUVV6VlUwdnc0UT09'
    const key = 'X7*&^EgM&CcXGj%=';
    const iv = '!tr3CBz&#r^*q5@U';
    const decode = atob(str);
    const str1 = this.decrypt(decode, key, iv);
    this.login();
  }
}
</script>

<template>
  <view class="page">
    <view class="form">
      <view class="logo-wrap">
        <image src="/static/images/login_logo.png" mode="widthFix" style="width: 250px;height: 75px;" class="logo"></image>
      </view>
      <view class="btns">
        <!--      手机快捷登录-->
        <u-button
            type="primary"
            :loading="loading"
            loadingText="登录中..."
            @click="loginClick"
            v-if="!this.agreement.includes('agreement') || hasPhone"
        >手机号快捷登录</u-button>
        <u-button
            v-else
            type="primary"
            open-type="getPhoneNumber"
            :loading="loading"
            loadingText="登录中..."
            @getphonenumber="handlePhoneNumber"
        >手机号快捷登录</u-button>

<!--        <button open-type="getPhoneNumber" @click="getPhoneNumber">获取手机号</button>-->
      </view>
    </view>

    <view class="ag-wrap">
      <view class="agreement cell">
        <view class="cell-hd">
          <u-checkbox-group
              v-model="agreement"
              placement="column"
              @change="groupChange"
          >
            <u-checkbox
                label=" "
                name="agreement"
                @click="toAgreement"
                activeColor="#3c9cff"
                inactiveColor="#3c9cff"
                size="14"
            >
            </u-checkbox>
          </u-checkbox-group>
        </view>
        <view class="cell-bd">
          <text>请阅读并同意<text class="link" @click="toAgreement">《⽤户服务协议和隐私政策》</text></text>
        </view>
        <!--        <u-radio-group-->
        <!--            v-model="agreement"-->
        <!--            placement="column"-->
        <!--            @change="groupChange"-->
        <!--        >-->
        <!--          <u-radio-->
        <!--              label="1"-->
        <!--              name="11"-->
        <!--              @click="toAgreement"-->
        <!--          >-->
        <!--            <text @click="toAgreement">请阅读并同意《⽤户服务协议和隐私政策》</text>-->
        <!--          </u-radio>-->
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.form{
  background-size: 100% 100%;
  box-sizing: border-box;
  padding: 0 75rpx;
  position: relative;
  //top: 50%;
  transform: translateY(50%);
  .logo-wrap{
    width: 579rpx;
    margin: 0 auto;
    .logo{
      width: 100%;
    }
  }

  .btns{
    margin-top: 163rpx;
  }
}

.ag-wrap{
  position: absolute;
  bottom: 35rpx;
  margin: auto;
  width: 100%;
  text-align: center;
  padding-left: 115rpx;
}
.agreement{
  text-align: left;
  font-size: 28rpx;
  margin: auto;
  color: #999999;
  .link{
    color: #3C9CFF;
  }
}
</style>
